<?php

use think\Db;

/**
 * @param
 * @return bool 2
 */
function is_login() {
    if (isset($_SESSION['admin_id']) && $_SESSION['admin_id'] > 0) {
        return $_SESSION['admin_id'];
    } else {
        return false;
    }
}

/**
 * 记录帐户变动
 * @param   int     $user_id        用户id
 * @param   float   $user_money     可用余额变动
 * @param   int     $pay_points     消费积分变动
 * @param   string  $desc    变动说明
 * @param   float   distribut_money 分佣金额
 * @param int $order_id 订单id
 * @param string $order_sn 订单sn
 * @return  bool
 */
function accountLog($user_id, $user_money = 0, $desc = '', $distribut_money = 0, $order_id = 0) {
    /* 插入帐户变动记录 */
    $account_log = array(
        'user_id' => $user_id,
        'user_money' => $user_money,
        'change_time' => time(),
        'desc' => $desc,
        'order_id' => $order_id
    );
    $update_data = array(
        'user_money' => ['exp', 'user_money+' . $user_money],
        'distribut_money' => ['exp', 'distribut_money+' . $distribut_money],
    );
//    $update = Db::name('users')->where('user_id', $user_id)->update($update_data);
    if ($update !== false) {
        M('account_log')->add($account_log);
        return true;
    } else {
        return false;
    }
}

/**
 * 写入静态页面缓存
 */
function write_html_cache($html) {
    $html_cache_arr = C('HTML_CACHE_ARR');
    $request = think\Request::instance();
    $m_c_a_str = $request->module() . '_' . $request->controller() . '_' . $request->action(); // 模块_控制器_方法
    $m_c_a_str = strtolower($m_c_a_str);
    //exit('write_html_cache写入缓存<br/>');
    if (is_array($html_cache_arr)) {
        foreach ($html_cache_arr as $key => $val) {
            $val['mca'] = strtolower($val['mca']);
            if ($val['mca'] != $m_c_a_str) //不是当前 模块 控制器 方法 直接跳过
                continue;

            //if(!is_dir(RUNTIME_PATH.'html'))
            //mkdir(RUNTIME_PATH.'html');
            //$filename =  RUNTIME_PATH.'html'.DIRECTORY_SEPARATOR.$m_c_a_str;
            $filename = $m_c_a_str;
            // 组合参数  
            if (isset($val['p'])) {
                foreach ($val['p'] as $k => $v)
                    $filename .= '_' . $_GET[$v];
            }
            $filename .= '.html';
            \think\Cache::set($filename, $html);
            //file_put_contents($filename, $html);
        }
    }
}

/**
 * 读取静态页面缓存
 */
function read_html_cache() {
    $html_cache_arr = C('HTML_CACHE_ARR');
    $request = think\Request::instance();
    $m_c_a_str = $request->module() . '_' . $request->controller() . '_' . $request->action(); // 模块_控制器_方法
    $m_c_a_str = strtolower($m_c_a_str);
    //exit('read_html_cache读取缓存<br/>');
    foreach ($html_cache_arr as $key => $val) {
        $val['mca'] = strtolower($val['mca']);
        if ($val['mca'] != $m_c_a_str) //不是当前 模块 控制器 方法 直接跳过
            continue;

        //$filename =  RUNTIME_PATH.'html'.DIRECTORY_SEPARATOR.$m_c_a_str;
        $filename = $m_c_a_str;
        // 组合参数        
        if (isset($val['p'])) {
            foreach ($val['p'] as $k => $v)
                $filename .= '_' . $_GET[$v];
        }
        $filename .= '.html';
        $html = \think\Cache::get($filename);
        if ($html) {
            //echo file_get_contents($filename);
            echo \think\Cache::get($filename);
            exit();
        }
    }
}

/**
 * 获取缓存或者更新缓存
 * @param string $config_key 缓存文件名称
 * @param array $data 缓存数据  array('k1'=>'v1','k2'=>'v3')
 * @return array or string or bool
 */
function tpCache($config_key, $data = array()) {
    $param = explode('.', $config_key);
    if (empty($data)) {
        //如$config_key=shop_info则获取网站信息数组
        //如$config_key=shop_info.logo则获取网站logo字符串
        $config = F($param[0], '', TEMP_PATH); //直接获取缓存文件
        if (empty($config)) {
            //缓存文件不存在就读取数据库
            $res = D('config')->where("inc_type", $param[0])->select();
            if ($res) {
                foreach ($res as $k => $val) {
                    $config[$val['name']] = $val['value'];
                }
                F($param[0], $config, TEMP_PATH);
            }
        }
        if (count($param) > 1) {
            return $config[$param[1]];
        } else {
            return $config;
        }
    } else {
        //更新缓存
        $result = D('config')->where("inc_type", $param[0])->select();
        if ($result) {
            foreach ($result as $val) {
                $temp[$val['name']] = $val['value'];
            }
            foreach ($data as $k => $v) {
                $newArr = array('name' => $k, 'value' => trim($v), 'inc_type' => $param[0]);
                if (!isset($temp[$k])) {
                    M('config')->add($newArr); //新key数据插入数据库
                } else {
                    if ($v != $temp[$k])
                        M('config')->where("name", $k)->save($newArr); //缓存key存在且值有变更新此项
                }
            }
            //更新后的数据库记录
            $newRes = D('config')->where("inc_type", $param[0])->select();
            foreach ($newRes as $rs) {
                $newData[$rs['name']] = $rs['value'];
            }
        } else {
            foreach ($data as $k => $v) {
                $newArr[] = array('name' => $k, 'value' => trim($v), 'inc_type' => $param[0]);
            }
            M('config')->insertAll($newArr);
            $newData = $data;
        }
        return F($param[0], $newData, TEMP_PATH);
    }
}

/**
 * 获取某个商品分类的 儿子 孙子  重子重孙 的 id
 * @param type $cat_id
 */
function getCatGrandson($cat_id) {
    $GLOBALS['catGrandson'] = array();
    $GLOBALS['category_id_arr'] = array();
    // 先把自己的id 保存起来
    $GLOBALS['catGrandson'][] = $cat_id;
    // 把整张表找出来
    $GLOBALS['category_id_arr'] = M('GoodsCategory')->cache(true, TPSHOP_CACHE_TIME)->getField('gct_id,parent_id');
    // 先把所有儿子找出来
    $son_id_arr = M('GoodsCategory')->where("parent_id", $cat_id)->cache(true, TPSHOP_CACHE_TIME)->getField('gct_id', true);
    foreach ($son_id_arr as $k => $v) {
        getCatGrandson2($v);
    }
    return $GLOBALS['catGrandson'];
}

/**
 * 递归调用找到 重子重孙
 * @param type $cat_id
 */
function getCatGrandson2($cat_id) {
    $GLOBALS['catGrandson'][] = $cat_id;
    foreach ($GLOBALS['category_id_arr'] as $k => $v) {
        // 找到孙子
        if ($v == $cat_id) {
            getCatGrandson2($k); // 继续找孙子
        }
    }
}

/**
 * jqGrid 原生查询方法
 * @param type $sql 算起来语句
 * @param type $group 分组字段
 * @return type array();
 */
function JQGrid($sql, $group = '', $count_sql = '') {
    $responce = new \stdClass();
    //JQGrid数据
    $page = $_GET['page']; // get the requested page
    $limit = $_GET['rows']; // get how many rows we want to have into the grid
    $sidx = $_GET['sidx']; // get index row - i.e. user click to sort
    $sord = $_GET['sord']; // get the direction
    $order = '';
    if ($sidx != false) {
        $order = " ORDER BY " . $sidx . " " . $sord;
    }
    //$sidx = 1;
    if (!empty($group)) {
        $sql .= " GROUP BY " . $group;
    }
    if (empty($count_sql)) {
        $countinfo = DB::query($sql);
        $count = count($countinfo);
    } else {
        $count = DB::query($count_sql)[0]["num"];
    }
    if ($count > 0) {
        $total_pages = ceil($count / $limit);
    } else {
        $total_pages = 0;
    }
    if ($page > $total_pages)
        $page = $total_pages;
    $start = $limit * $page - $limit; // do not put $limit*($page - 1)
    if ($start < 0) {
        $start = 0;
    }

    $sql .= $order . " LIMIT " . $start . "," . $limit;
    $row = DB::query($sql);
//show_bug($sql);
    $responce->page = $page;
    $responce->total = $total_pages;
    $responce->records = $count;
    $responce->rows = $row;
    return $responce;
}

/**
 * jqGrid tp查询方法
 * @param type $sql 算起来语句
 * @param type $group 分组字段
 * @return type array();
 */
function JQGrid_tp($sql_parm = array()) {
    $responce = new \stdClass();
    //JQGrid数据
    $page = $_GET['page']; // get the requested page
    $limit = $_GET['rows']; // get how many rows we want to have into the grid
    $sidx = $_GET['sidx']; // get index row - i.e. user click to sort
    $sord = $_GET['sord']; // get the direction
    if (!empty($sql_parm['group'])) {
        $sql_parm['mod'] = $sql_parm['mod']->GROUP($sql_parm['group']);
    }
    if (empty($sql_parm['count_sql'])) {
        $ref_mod = (clone $sql_parm['mod']);
        $count = $ref_mod->count();
    } else {
        $count = DB::query($sql_parm['count_sql'])[0]["num"];
    }
    if (!empty($sql_parm['field'])) {
        $sql_parm['mod'] = $sql_parm['mod']->field($sql_parm['field']);
    }
    if ($sidx != false) {
        $sql_parm['mod'] = $sql_parm['mod']->order($sidx . ' ' . $sord);
    }
    if ($count > 0) {
        $total_pages = ceil($count / $limit);
    } else {
        $total_pages = 0;
    }
    if ($page > $total_pages)
        $page = $total_pages;
    $start = $limit * $page - $limit; // do not put $limit*($page - 1)
    if ($start < 0) {
        $start = 0;
    }
    $sql_parm['mod'] = $sql_parm['mod']->limit($start . "," . $limit);
    $row = $sql_parm['mod']->select();
//show_bug($sql);
    $responce->page = $page;
    $responce->total = $total_pages;
    $responce->records = $count;
    $responce->rows = $row;
    return $responce;
}

/**
 * jqGrid 数组处理
 * @param type $arr
 * @return type
 */
function JQGrid_array($arr) {
    $responce = new \stdClass();
    $page = I('page'); // get the requested page
    $limit = I('rows'); // get how many rows we want to have into the grid
    $sidx = I('sidx'); // get index row - i.e. user click to sort
    $sord = I('sord'); // get the direction
    $count = count($arr);
    if ($count > 0) {
        $total_pages = ceil($count / $limit);
    } else {
        $total_pages = 0;
    }
    if ($page > $total_pages)
        $page = $total_pages;
    $start = $limit * $page - $limit; // do not put $limit*($page - 1)
    if ($start < 0) {
        $start = 0;
    }

    //按下面字段排序
    $score = array();
    foreach ($arr as $k => $v) {
        $score[$k] = $v[$sidx];
    }
    //按下面的方式（升序/降序）
    $sordStr = '';
    if ($sord == 'asc' || $sord == 'ASC') {
        $sordStr = SORT_ASC;
    } elseif ($sord == 'desc' || $sord == 'DESC') {
        $sordStr = SORT_DESC;
    }

    array_multisort($score, $sordStr, SORT_REGULAR, $arr);

    $row = array_slice($arr, $start, $limit);
    $responce->page = $page;
    $responce->total = $total_pages;
    $responce->records = $count;
    $responce->rows = $row;
    return $responce;
}

/**
 * 检测是否能够发送短信
 * @param unknown $scene
 * @return multitype:number string
 */
function checkEnableSendSms($scene) {

    $scenes = C('SEND_SCENE');
    $sceneItem = $scenes[$scene];
    if (!$sceneItem) {
        return array("status" => -1, "msg" => "场景参数'scene'错误!");
    }
    $key = $sceneItem[2];
    $sceneName = $sceneItem[0];
    $config = tpCache('sms');
    $smsEnable = $config[$key];

    if (!$smsEnable) {
        return array("status" => -1, "msg" => "['$sceneName']发送短信被关闭'");
    }
    //判断是否添加"注册模板"
    $size = M('sms_template')->where("send_scene", $scene)->count('tpl_id');
    if (!$size) {
        return array("status" => -1, "msg" => "请先添加['$sceneName']短信模板");
    }

    return array("status" => 1, "msg" => "可以发送短信");
}

/**
 * 获取用户信息
 * @param $user_id_or_name  用户id 邮箱 手机 第三方id
 * @param int $type  类型 0 user_id查找 1 邮箱查找 2 手机查找 3 第三方唯一标识查找
 * @param string $oauth  第三方来源
 * @return mixed
 */
function get_user_info($user_id_or_name, $type = 0, $oauth = '') {
    $map = array();
    if ($type == 0)
        $map['user_id'] = $user_id_or_name;
    if ($type == 5)
        $map['username'] = $user_id_or_name;
    if ($type == 1)
        $map['email'] = $user_id_or_name;
    if ($type == 2)
        $map['mobile'] = $user_id_or_name;
    if ($type == 3) {
        $map['openid'] = $user_id_or_name;
        $map['oauth'] = $oauth;
    }
    if ($type == 4) {
        $map['unionid'] = $user_id_or_name;
        $map['oauth'] = $oauth;
    }
    $user = M('user')->where($map)->find();
    return $user;
}

/**
 * 获取商品一二三级分类
 * @return type
 */
function get_goods_category_tree() {
    $tree = $arr = $result = array();
    $cat_list = M('goods_category')->where("is_show = 1")->field('gct_id,name,mobile_name,letter,parent_id,parent_id_path,sort_order,level,image,color,note')->order('sort_order')->select(); //所有分类
    if ($cat_list) {
        foreach ($cat_list as $val) {
            if ($val['level'] == 2) {
                $arr[$val['parent_id']][] = $val;
            }
            if ($val['level'] == 3) {
                $crr[$val['parent_id']][] = $val;
            }
            if ($val['level'] == 1) {
                $tree[] = $val;
            }
        }
        foreach ($arr as $k => $v) {
            foreach ($v as $kk => $vv) {
                $arr[$k][$kk]['sub_menu'] = empty($crr[$vv['gct_id']]) ? array() : $crr[$vv['gct_id']];
            }
        }
        foreach ($tree as $val) {
            $val['tmenu'] = empty($arr[$val['gct_id']]) ? array() : $arr[$val['gct_id']];
            $result[$val['gct_id']] = $val;
        }
    }
    return $result;
}

/**
 *  商品缩略图 给于标签调用 拿出商品表的 original_img 原始图来裁切出来的
 * @param type $goods_id  商品id
 * @param type $width     生成缩略图的宽度
 * @param type $height    生成缩略图的高度
 */
function goods_thum_images($goods_id, $width, $height, $type = 0) {
    if (empty($goods_id))
        return '';
    //判断缩略图是否存在
    if ($type == 0) {
        $path = "public/upload/goods/thumb/$goods_id/";
    } else {
        $path = "public/upload/article/thumb/$goods_id/";
    }
    $goods_thumb_name = "goods_thumb_{$goods_id}_{$width}_{$height}";
    // 这个商品 已经生成过这个比例的图片就直接返回了
    if (is_file($path . $goods_thumb_name . '.jpg'))
        return '/' . $path . $goods_thumb_name . '.jpg';
    if (is_file($path . $goods_thumb_name . '.jpeg'))
        return '/' . $path . $goods_thumb_name . '.jpeg';
    if (is_file($path . $goods_thumb_name . '.gif'))
        return '/' . $path . $goods_thumb_name . '.gif';
    if (is_file($path . $goods_thumb_name . '.png'))
        return '/' . $path . $goods_thumb_name . '.png';
    if ($type == 0) {
        $original_img = M('Goods')->cache(true, 3600)->where("goods_id", $goods_id)->getField('original_img');
    } else {
        $original_img = M('Article')->cache(true, 3600)->where("article_id", $goods_id)->getField('image');
    }
    if (empty($original_img)) {
        df_thum_images($width, $height);
        return '/public/images/icon_goods_thumb_empty_' . $width . '_' . $height . '.jpeg';
    }
    $ossClient = new \app\common\logic\OssLogic;
    if (($ossUrl = $ossClient->getGoodsThumbImageUrl($original_img, $width, $height))) {
        return $ossUrl;
        if ($width > 0 && $height > 0) {
            return $ossUrl;
        } else {
            return $original_img;
        }
    }
    M('goods')->update(array('goods_id' => $goods_id, 'is_new' => 99));
    $original_img = '.' . $original_img; // 相对路径
    if (!is_file($original_img)) {
        return '/public/images/icon_goods_thumb_empty_' . $width . '_' . $height . '.jpg';
    }
    try {
        vendor('topthink.think-image.src.Image');
        if (strstr(strtolower($original_img), '.gif')) {
            vendor('topthink.think-image.src.image.gif.Encoder');
            vendor('topthink.think-image.src.image.gif.Decoder');
            vendor('topthink.think-image.src.image.gif.Gif');
        }
        $image = \think\Image::open($original_img);
        $goods_thumb_name = $goods_thumb_name . '.' . $image->type();
        // 生成缩略图
        !is_dir($path) && mkdir($path, 0777, true);
        // 参考文章 http://www.mb5u.com/biancheng/php/php_84533.html  改动参考 http://www.thinkphp.cn/topic/13542.html
        $image->thumb($width, $height, 2)->save($path . $goods_thumb_name, NULL, 100); //按照原图的比例生成一个最大为$width*$height的缩略图并保存
        //图片水印处理
        $water = tpCache('water');
        if ($water['is_mark'] == 1) {
            $imgresource = './' . $path . $goods_thumb_name;
            if ($width > $water['mark_width'] && $height > $water['mark_height']) {
                if ($water['mark_type'] == 'img') {
                    //检查水印图片是否存在
                    $waterPath = "." . $water['mark_img'];
                    if (is_file($waterPath)) {
                        $quality = $water['mark_quality'] ?: 80;
                        $waterTempPath = dirname($waterPath) . '/temp_' . basename($waterPath);
                        $image->open($waterPath)->save($waterTempPath, null, $quality);
                        $image->open($imgresource)->water($waterTempPath, $water['sel'], $water['mark_degree'])->save($imgresource);
                        @unlink($waterTempPath);
                    }
                } else {
                    //检查字体文件是否存在,注意是否有字体文件
                    $ttf = './hgzb.ttf';
                    if (file_exists($ttf)) {
                        $size = $water['mark_txt_size'] ?: 30;
                        $color = $water['mark_txt_color'] ?: '#000000';
                        if (!preg_match('/^#[0-9a-fA-F]{6}$/', $color)) {
                            $color = '#000000';
                        }
                        $transparency = intval((100 - $water['mark_degree']) * (127 / 100));
                        $color .= dechex($transparency);
                        $image->open($imgresource)->text($water['mark_txt'], $ttf, $size, $color, $water['sel'])->save($imgresource);
                    }
                }
            }
        }
        $img_url = '/' . $path . $goods_thumb_name;
        M('goods')->update(array('goods_id' => $goods_id, 'is_new' => 0));
        return $img_url;
    } catch (think\Exception $e) {

        return $original_img;
    }
}

/**
 *  默认缩略图 用于各种不同大小默认图
 * @param type $width     生成缩略图的宽度
 * @param type $height    生成缩略图的高度
 */
function df_thum_images($width, $height) {
    $df_path = "public/images/";
    $df_thumb_name = "icon_goods_thumb_empty_{$width}_{$height}";
    $original_img = 'public/images/icon_goods_thumb_df.jpg';
    if (is_file($df_path . $df_thumb_name . '.jpeg'))
        return;
    try {
        vendor('topthink.think-image.src.Image');
        if (strstr(strtolower($original_img), '.gif')) {
            vendor('topthink.think-image.src.image.gif.Encoder');
            vendor('topthink.think-image.src.image.gif.Decoder');
            vendor('topthink.think-image.src.image.gif.Gif');
        }
        $image = \think\Image::open($original_img);
        $df_thumb_name = $df_thumb_name . '.' . $image->type();
        // 生成缩略图
        !is_dir($df_path) && mkdir($df_path, 0777, true);
        // 参考文章 http://www.mb5u.com/biancheng/php/php_84533.html  改动参考 http://www.thinkphp.cn/topic/13542.html
        $image->thumb($width, $height, 2)->save($df_path . $df_thumb_name, NULL, 100); //按照原图的比例生成一个最大为$width*$height的缩略图并保存
        //图片水印处理
        $water = tpCache('water');
        if ($water['is_mark'] == 1) {
            $imgresource = './' . $df_path . $df_thumb_name;
            if ($width > $water['mark_width'] && $height > $water['mark_height']) {
                if ($water['mark_type'] == 'img') {
                    //检查水印图片是否存在
                    $waterPath = "." . $water['mark_img'];
                    if (is_file($waterPath)) {
                        $quality = $water['mark_quality'] ?: 80;
                        $waterTempPath = dirname($waterPath) . '/temp_' . basename($waterPath);
                        $image->open($waterPath)->save($waterTempPath, null, $quality);
                        $image->open($imgresource)->water($waterTempPath, $water['sel'], $water['mark_degree'])->save($imgresource);
                        @unlink($waterTempPath);
                    }
                } else {
                    //检查字体文件是否存在,注意是否有字体文件
                    $ttf = './hgzb.ttf';
                    if (file_exists($ttf)) {
                        $size = $water['mark_txt_size'] ?: 30;
                        $color = $water['mark_txt_color'] ?: '#000000';
                        if (!preg_match('/^#[0-9a-fA-F]{6}$/', $color)) {
                            $color = '#000000';
                        }
                        $transparency = intval((100 - $water['mark_degree']) * (127 / 100));
                        $color .= dechex($transparency);
                        $image->open($imgresource)->text($water['mark_txt'], $ttf, $size, $color, $water['sel'])->save($imgresource);
                    }
                }
            }
        }
        $img_url = '/' . $df_path . $df_thumb_name;
        return $img_url;
    } catch (think\Exception $e) {
        return false;
    }
}

/**
 * 商品相册缩略图
 */
function get_sub_images($sub_img, $goods_id, $width, $height) {
    //判断缩略图是否存在
    $path = "public/upload/goods/thumb/$goods_id/";
    $goods_thumb_name = "goods_sub_thumb_{$sub_img['img_id']}_{$width}_{$height}";

    //这个缩略图 已经生成过这个比例的图片就直接返回了
    if (is_file($path . $goods_thumb_name . '.jpg'))
        return '/' . $path . $goods_thumb_name . '.jpg';
    if (is_file($path . $goods_thumb_name . '.jpeg'))
        return '/' . $path . $goods_thumb_name . '.jpeg';
    if (is_file($path . $goods_thumb_name . '.gif'))
        return '/' . $path . $goods_thumb_name . '.gif';
    if (is_file($path . $goods_thumb_name . '.png'))
        return '/' . $path . $goods_thumb_name . '.png';

    $ossClient = new \app\common\logic\OssLogic;
    if (($ossUrl = $ossClient->getGoodsAlbumThumbUrl($sub_img['image_url'], $width, $height))) {
        return $ossUrl;
    }

    $original_img = '.' . $sub_img['image_url']; //相对路径
    if (!is_file($original_img)) {
        return '/public/images/icon_goods_thumb_empty_300.png';
    }

    vendor('topthink.think-image.src.Image');
    if (strstr(strtolower($original_img), '.gif')) {
        vendor('topthink.think-image.src.image.gif.Encoder');
        vendor('topthink.think-image.src.image.gif.Decoder');
        vendor('topthink.think-image.src.image.gif.Gif');
    }
    $image = \think\Image::open($original_img);

    !is_dir($path) && mkdir($path, 0777, true);
    $goods_thumb_name = $goods_thumb_name . '.' . $image->type();

    // 生成缩略图
    $image->thumb($width, $height, 2)->save($path . $goods_thumb_name, NULL, 100); //按照原图的比例生成一个最大为$width*$height的缩略图并保存
    return '/' . $path . $goods_thumb_name;
}

/**
 * 格式化金额
 * @param type $a
 * @param type $n
 * @return type
 */
function num_format($a, $n) {
    return number_format($a, $n);
}

/**
 * 下载远程图片保存到本地
 * @access public
 * @author      lxhui<772932587@qq.com>
 * @since 1.0
 * @return array
 * @params string $url 远程图片地址
 * @params string $save_dir 需要保存的地址
 * @params string $filename 保存文件名
 */
function download($url, $save_dir = './public/upload/goods_tmp/', $filename = '') {
    if (trim($save_dir) == '')
        $save_dir = './';

    if (trim($filename) == '') {//保存文件名
        $allowExt = array('.gif', '.jpg', '.jpeg', '.png', '.bmp');
        $ext = strrchr($url, '.');
        if (!in_array($ext, $allowExt))
            return array('file_name' => '', 'save_path' => '', 'error' => 3);

        $filename = time() . $ext;
    }
    if (0 !== strrpos($save_dir, '/'))
        $save_dir .= '/';

    //创建保存目录
    if (!file_exists($save_dir) && !mkdir($save_dir, 0777, true))
        return array('file_name' => '', 'save_path' => '', 'error' => 5);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    $file = curl_exec($ch);
    curl_close($ch);
    $filename = pathinfo($url, PATHINFO_BASENAME);
    $resource = fopen($save_dir . $filename, 'a');
    fwrite($resource, $file);
    fclose($resource);
    unset($file, $url);
    return array('file_name' => $filename, 'save_path' => $save_dir . $filename, 'error' => 0);
}

/**
 * 无限递归
 * @param type $arr
 * @param type $id
 * @param type $level
 * @param type $kay_name
 * @return type
 */
function infinite_recursion($arr, $id, $level, $kay_name = array('id', 'pid', 'level', 'children')) {
    $list = array();
    foreach ($arr as $k => $v) {
        if ($v[$kay_name[1]] == $id) {
            $v[$kay_name[2]] = $level;
            $v[$kay_name[3]] = infinite_recursion($arr, $v[$kay_name[0]], $level + 1, $kay_name);
            $list[] = $v;
        }
    }
    return $list;
}

/**
 * 追加写入内容
 * @param type $file_path
 * @param type $content
 */
function write_file($file_path, $content) {
    if (file_exists($file_path)) {
        $fp = fopen($file_path, "r");
        $str = "";
        while (!feof($fp)) {
            $str .= fgets($fp); //逐行读取。如果fgets不写length参数，默认是读取1k。
        }
    }
    $myfile = fopen($file_path, "w") or die("Unable to open file!");
    fwrite($myfile, $str . $content);
    fclose($myfile);
}
//多维数组根据某个字段进行拆分合并
function arys_emmm(){
     $attribute = array(
            0 => array("id_attribute" => 15, "group_name" => "Disk space", "name" => "8Go"),
            1 => array("id_attribute" => 48, "group_name" => "Software Languages", "name" => "Englist"),
            2 => array("id_attribute" => 34, "group_name" => "HDD Type", "name" => "IBM T30"),
            3 => array("id_attribute" => 49, "group_name" => "Software Languages", "name" => "Deutsch"),
            4 => array("id_attribute" => 16, "group_name" => "Disk space", "name" => "16Go"),
            5 => array("id_attribute" => 40, "group_name" => "HDD Type", "name" => "IBM T40"),
            6 => array("id_attribute" => 17, "group_name" => "Disk space", "name" => "32Go"),
            7 => array("id_attribute" => 50, "group_name" => "Software", "Languages name" => "Français "),
            8 => array("id_attribute" => 34, "group_name" => "HDD Type", "name" => "IBM T30"),
            9 => array("id_attribute]" => 15, "group_name" => "Disk space", "name" => "8Go"),
            10 => array("id_attribute" => 46, "group_name" => "HDD Type", "name" => "IBM T42"),
            11 => array("id_attribute" => 49, "group_name" => "Software Languages", "name" => "Deutsch"),
            12 => array("id_attribute" => 17, "group_name" => "Disk space", "name" => "32Go"),
            13 => array("id_attribute" => 40, "group_name" => "HDD Type", "name" => "IBM T40"),
            14 => array("id_attribute" => 49, "group_name" => "Software Languages", "name" => "Deutsch"),
            15 => array("id_attribute" => 48, "group_name" => "Software Languages", "name" => "Englist")
        );
        $a = array_values(array_reduce($attribute, function($v, $w) {
                    $group_name = $w['group_name'];
                    unset($w['group_name']);
                    $v[$group_name]['group_name'] = $group_name;
                    $v[$group_name]['item'][] = $w;
                    return $v;
                }));
                var_dump($a);
}
//多维数组合并   show_bug($this->array_merge_multi($ary,$ary2));
function array_merge_multi() {
	$args = func_get_args();
	
	if ( !isset( $args[0] ) && !array_key_exists( 0, $args ) ) {
		return array();
	}
	
	$arr = array();
	foreach ( $args as $key => $value ) {
		if ( is_array( $value ) ) {
			foreach ( $value as $k => $v ) {
				if ( is_array( $v ) ) {
					if ( !isset( $arr[$k] ) && !array_key_exists( $k, $arr ) ) {
						$arr[$k] = array();
					}
					$arr[$k] = $this->array_merge_multi( $arr[$k], $v );
				} else {
					$arr[$k] = $v;
				}
			}
		}
	}
	return $arr;
} 